package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IPermissionService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    public String list(Model model, QueryObject qo) {
        PageInfo<Permission> pageInfo = permissionService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "permission/list";
    }

    @RequestMapping("/input")
    public String input(Model model, Long id) {
        //查询所有权限
        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions", permissions);

        if (id != null) {
            Permission permission = permissionService.select(id);
            model.addAttribute("permission", permission);
        }
        return "permission/input";
    }

    @RequestMapping("/saveOrUpdate")
    public String insertOrUpdate(Permission permission) {
        if (permission.getId() != null) {
            permissionService.update(permission);
        } else {
            permissionService.insert(permission);
        }
        return "redirect:/permission/list.do";
    }

    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            permissionService.delete(id);
        }
        return "redirect:/permission/list.do";
    }

    @RequestMapping("/reload")
    @ResponseBody
    public JsonResult reload() {
        try {
            permissionService.reload();
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(false, "加载失败");
    }
}
